package com.founder.bdyx;

import com.founder.bdyx.core.pdfUtil.CreateTemplate;
import com.founder.bdyx.core.pdfUtil.MyHeaderFooter;
import com.founder.bdyx.core.pdfUtil.Watermark;
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.draw.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.ResourceUtils;

import java.awt.*;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class PdfReport {

    public static void main(String[] args) throws Exception {
//        String[] files = {"d:/pdf/210414000001.pdf","d:/pdf/210419000001.pdf","d:/pdf/210419000001.pdf","d:/pdf/210419000001.pdf","d:/pdf/210419000001.pdf"};
//        String newFile = "d:/pdf/merge.pdf";
//        CreateTemplate.mergePdfFiles(files,newFile);

//        File file = new File("d:/pdf/210414000001.pdf");
//        System.out.println(file.getName());
//        System.out.println(file.getPath());
//        System.out.println(file.getCanonicalPath());

        String soap = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:urn=\"urn:hl7-org:v3\">\n" +
                "   <soap:Header/>\n" +
                "   <soap:Body>\n" +
                "      <urn:HIPMessageServer>\n" +
                "         <!--Optional:-->\n" +
                "         <action>aaa</action>\n" +
                "         <!--Optional:-->\n" +
                "         <message>bbb</message>\n" +
                "      </urn:HIPMessageServer>\n" +
                "   </soap:Body>\n" +
                "</soap:Envelope>";
        /**
         *
         "        //     + '<![CDATA[';\n" +
         "        // // 请求交易参数\n" +
         "        // data = data + restr;\n" +
         "        // data = data + ']]></arg0>'\n" +
         */
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost("http://111.111.119.32:7802/eval-web/webservice/HIPService?wsdl");
            httpPost.setHeader("Content-Type", "application/soap+xml");
//            httpPost.setHeader("SOAPAction", "urn:hl7-org:v3");
            InputStreamEntity entity = new InputStreamEntity(new ByteArrayInputStream(soap.getBytes()));
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String back = EntityUtils.toString(responseEntity);
                System.out.println("httpClient返回soap：" + back);
//                System.out.println("httpClient返回结果：" + parseResult(back));
            } else {
                System.out.println("HttpClinet返回状态码：" + response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 添加内容 插入Chunk, Phrase, Paragraph, List
     *
     * @author ShaoMin
     * @throws Exception
     */
    public static void addContent() throws Exception {
        Document document = new Document(PageSize.A4);
        PdfWriter.getInstance(document, new FileOutputStream("d:/pdf/content.pdf"));
        document.open();

        // 1-Chunk块对象: a String, a Font, and some attributes
        document.add(new Chunk("中文输出： ", getChineseFont()));

        Chunk tChunk2 = new Chunk("输出的内容", getChineseFont());
        tChunk2.setBackground(BaseColor.CYAN, 1f, 0.5f, 1f, 1.5f); // 设置背景色
        tChunk2.setTextRise(6); // 上浮
        tChunk2.setUnderline(0.2f, -2f); // 下划线
        document.add(tChunk2);

        document.add(Chunk.NEWLINE); // 新建一行
        // document.add(new Phrase("Phrase page  :")); //会上浮，不知道原因？？

        // 2-Phrase短语对象: a List of Chunks with leading
        document.add(new Phrase("Phrase page  :"));

        Phrase tPhrase = new Phrase();
        Chunk name = new Chunk("China");
        name.setUnderline(0.2f, -2f);
        tPhrase.add(name);
        tPhrase.add(Chunk.NEWLINE);// 放在容器中好用
        tPhrase.add(new Chunk("换行了 :", getChineseFont()));
        tPhrase.add(new Chunk("chinese"));
        tPhrase.setLeading(14f);// 行间距
        document.add(tPhrase);

        // 这边就好用，上面是Chunk，就不好用
        // 放在段落或短语中又好用
        document.add(Chunk.NEWLINE);

        Phrase director2 = new Phrase();
        Chunk name2 = new Chunk("换行了---Japan", getChineseFont());
        name2.setUnderline(0.2f, -2f);
        director2.add(name2);
        director2.add(new Chunk(","));
        director2.add(new Chunk(" "));
        director2.add(new Chunk("japanese上浮下", getChineseFont()).setTextRise(3f));
        director2.setLeading(24);
        document.add(director2);

        // 3-Paragraph段落对象: a Phrase with extra properties and a newline
        document.add(new Paragraph("Paragraph page"));
        Paragraph info = new Paragraph();
        info.add(new Chunk("China "));
        info.add(new Chunk("chinese"));
        info.add(Chunk.NEWLINE); // 好用的
        info.add(new Phrase("Japan "));
        info.add(new Phrase("japanese"));
        info.setSpacingAfter(10f);// 设置段落下空白
        document.add(info);

        // 段落是比较好用的
        Paragraph tParagraph = new Paragraph("段落是文章中最基本的单位。内容上它具有一个相对完整的意思；在文章中，段具有换行的标。段是由句子或句群组成的，在文章中用于体现作者的思路发展或全篇文章的层次。有的段落只有一个句子，称为独句段，独句段一般是文章的开头段、结尾段、"
                + "过渡段强调段等特殊的段落。多数段落包括不止一个句子或句群，叫多句段。中文段落开头前一般空两个格。", getChineseFont());
        tParagraph.setAlignment(Element.ALIGN_JUSTIFIED);// 对齐方式

        tParagraph.setIndentationLeft(12);// 左缩进
        tParagraph.setIndentationRight(12);// 右缩进
        tParagraph.setFirstLineIndent(24);// 首行缩进

        tParagraph.setLeading(20f);// 行间距
        tParagraph.setSpacingBefore(5f);// 设置上空白
        tParagraph.setSpacingAfter(10f);// 设置段落下空白
        document.add(tParagraph);

        // 每个新的段落会另起一行
        tParagraph = new Paragraph("新的段落", getChineseFont());
        tParagraph.setAlignment(Element.ALIGN_CENTER);// 居中
        document.add(tParagraph);

        document.close();
    }

    public static void test(){
        try {
            Document document = new Document(PageSize.A4);
            PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("d://test.pdf"));
            document.open();
            Paragraph paragraph = new Paragraph();

            Chunk chunk = new Chunk("你好的");
            Chunk chunk2 = new Chunk("aaaaa content");

            chunk.append("ffffff");


            paragraph.add(chunk);
            paragraph.add(chunk2);

            document.add(paragraph);
            document.close();
        }catch (Exception e){

        }

    }

    /**
     * 外部链接
     */
    public static void test4(){
        try {
            Document document = new Document(PageSize.A4);
            PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("d://test4.pdf"));
            document.open();
            Chunk chunk = new Chunk("the lazy dog");
            chunk.setAnchor("http://www.baidu.com");
            document.add(chunk);
            document.close();
        }catch (Exception e ){

        }
    }

    /**
     * 输出示例 设置字体、所在位置等
     */
    public static void test3(){
        Document document = new Document(PageSize.A4);
        try {
            PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("d://test3.pdf"));
            document.open();
            BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            Font fontChinese = new Font(bfChinese,16,Font.NORMAL);
            document.add(new Paragraph("Hello World, Hello PDF Come On !!"));
            Paragraph paragraph = new Paragraph("中文内容",fontChinese);
            paragraph.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph);
            document.close();
        }catch (Exception e){

        }
    }

    /**
     * 设置
     * 页面大小 页边距
     */
    public static void test1(){
        Document document = new Document(PageSize.A4);
//        Rectangle pagesize = new Rectangle(200f,800f);//设置页面200*800
//        Document document = new Document(pagesize,20f,20f,20f,20f);//页边距

//        Rectangle rectangle = new Rectangle(PageSize.A4);
//        Document document = new Document(rectangle,50,50,50,50);
        try {
            PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("d://test1.pdf"));
            document.open();
            document.add(new Paragraph("hello world!"));
            document.close();
        }catch (Exception e){

        }
    }

    /**
     * 设置背景颜色 文档属性
     */
    public static void test2() {
        try {
            Rectangle rect = new Rectangle(PageSize.A4);
            rect.setBackgroundColor(BaseColor.GRAY);//设置背景颜色
            rect.setBorder(Rectangle.BOX);//border类型为box （四周都有）
            rect.setBorderColor(BaseColor.DARK_GRAY);
            rect.setBorderWidth(5);
            Document document = new Document(rect);
            PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("d://test2.pdf"));
            document.addTitle("标题");
            document.addAuthor("");
            document.addCreationDate();
            document.addCreator("");
            document.addSubject("");
            document.addKeywords("");
            document.addHeader("Expires","0");
            document.open();
            document.add(new Paragraph("Hello world!"));
            document.close();
        }catch (Exception e){

        }

    }

    public void mkpdf(){
        try {
            // 1.新建document对象
            Document document = new Document(PageSize.A4);// 建立一个Document对象

            // 2.建立一个书写器(Writer)与document对象关联
            File file = new File("D:\\210416000001.pdf");
            file.createNewFile();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            writer.setPageEvent(new Watermark("210416000001"));// 水印
//            writer.setPageEvent(new MyHeaderFooter());// 页眉/页脚

            // 3.打开文档
            document.open();
//            document.addTitle("Title@PDF-Java");// 标题
//            document.addAuthor("Author@umiz");// 作者
//            document.addSubject("Subject@iText pdf sample");// 主题
//            document.addKeywords("Keywords@iTextpdf");// 关键字
//            document.addCreator("Creator@umiz`s");// 创建者

            // 4.向文档中添加内容
            new CreateTemplate().execSheetTemplate(document);

            // 5.关闭文档
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Font getChineseFont(){
        BaseFont bfChinese = null;
        try {
            bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Font fontChinese = new Font(bfChinese,16,Font.NORMAL);
        return fontChinese;
    }

    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    public static boolean validPhoneNum(String checkType,String phoneNum){
        boolean flag=false;
        Pattern p1 = null;
        Pattern p2 = null;
        Matcher m = null;
        p1 = Pattern.compile("^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\\d{8}$");
        p2 = Pattern.compile("^(0[0-9]{2,3}\\-)?([1-9][0-9]{6,7})$");
        if("0".equals(checkType)){
            System.out.println(phoneNum.length());
            if(phoneNum.length()!=11){
                return false;
            }else{
                m = p1.matcher(phoneNum);
                flag = m.matches();
            }
        }else if("1".equals(checkType)){
            if(phoneNum.length()<11||phoneNum.length()>=16){
                return false;
            }else{
                m = p2.matcher(phoneNum);
                flag = m.matches();
            }
        }else if("2".equals(checkType)){
            if(!((phoneNum.length() == 11 && p1.matcher(phoneNum).matches())||(phoneNum.length()<16&&p2.matcher(phoneNum).matches()))){
                return false;
            }else{
                flag = true;
            }
        }
        return flag;
    }
}
